#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <cstring>
#include <iostream>
#include <string>
#include <unistd.h>
#include <functional>
#include <unordered_map>
#include "log.hpp"

// typedef std::function<std::string(const std::string&)> func_t;
typedef std::function<std::string(const std::string&, const std::string&, uint16_t)> func_t;
Log log;
enum
{
    SOCKET_ERR = 1,
    BIND_ERR
};
const int size = 1024;
const std::string defaultip = "0.0.0.0";
// const std::string defaultip = "47.120.76.102";
const u_int16_t defaultport = 8080;
class UdpServer
{
public:
    UdpServer(std::string ip = defaultip, u_int16_t port = defaultport) : _ip(ip), _port(port), _isrunning(false), _sockfd(0)
    {
    }
    ~UdpServer()
    {
        if(_sockfd < 0)
            close(_sockfd);
    }
    void Init()
    {
        // 1.创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd == -1)
        {
            log(Fatal, "socket fail:errno:%d, strerrno:%s\n", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
        log(Info, "socket success\n");
        // std::cout << _sockfd << std::endl;

        // 2.绑定端口号
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n == -1)
        {
            log(Fatal, "bind fail:errno:%d, strerrno:%s\n", errno, strerror(errno));
            exit(BIND_ERR);
        }
        log(Info, "bind success\n");
    }
    void CheackUser(uint16_t online_port, sockaddr_in& online)
    {
        std::unordered_map<uint16_t,  sockaddr_in>::iterator it = _peoinfo.find(online_port);
        if(it == _peoinfo.end())
        {
            _peoinfo.insert({online_port, online});
            log(Info, "add to user list success\n");
        }
        return;
    }
    void BroadCast(const std::string& message)
    {
        for(auto& c : _peoinfo)
        {
            sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&c.second, sizeof(c.second));
        }
    }
    void Run(func_t func)
    {
        _isrunning = true;
        char inbuffer[size];
        while (_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t s = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr*)&client, &len);
            if (s < 0)
            {
                log(Warning, "recvfrom error\n");
                continue;
            }
            inbuffer[s] = 0;
            std::string info = inbuffer;

            std::string clientip = inet_ntoa(client.sin_addr);
            uint16_t clientport = ntohs(client.sin_port);
            CheackUser(clientport, client);
            
            std::string echo_string = func(inbuffer, clientip, clientport);
            BroadCast(echo_string);
        }
    }

private:
    int _sockfd;
    std::string _ip;
    u_int16_t _port;
    bool _isrunning;
    std::unordered_map<uint16_t, sockaddr_in> _peoinfo;
};